<template>
  <div>
    <a-form-model
      layout="horizontal"
      :model="newsDetail"
      v-bind="{
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      }"
    >
      <a-form-model-item label="新闻标题">
        <a-input v-model.trim="newsDetail.title" />
      </a-form-model-item>
      <a-form-model-item label="封面图片" prop="name">
        <a-upload
          name="avatar"
          :headers="headers"
          accept="image/*"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="newsDetail.cover" :src="newsDetail.cover" alt="avatar" />
          <div v-else>
            <a-icon :type="photoLoading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="新闻描述">
        <a-textarea
          v-model.trim="newsDetail.sketch"
          :auto-size="{ minRows: 1, maxRows: 4 }"
        />
      </a-form-model-item>
      <a-form-model-item label="新闻内容">
        <wangEditor
          v-model="newsDetail.content"
          :disabled="wangEditorDisable"
        ></wangEditor>
      </a-form-model-item>
    </a-form-model>
    <div class="actions">
      <a-button type="primary" @click="showModal">
        提交
      </a-button>
      <a-button type="primary" @click="back"> 返回 </a-button>
    </div>
    <a-modal
      centered
      title="提交"
      v-model="visible"
      @ok="submit"
      @cancel="cancel"
    >
      <p>确认提交？</p>
    </a-modal>
  </div>
</template>

<script>
import wangEditor from '@/pages/components/wangEditor/index.vue';
import getCookie from '@/utils/getCookie';
import { mapGetters } from 'vuex';
import {
  getNewsByIdApi,
  editNewsApi,
  addNewsApi,
} from '@/services/webApi/news';
import { UPLOAD } from '@/services/webApi/api';
// import { getNewsByIdAdminApi } from '@/services/superAdmin';
// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener("load", () => callback(reader.result));
//   reader.readAsDataURL(img);
// }
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  components: { wangEditor },
  data() {
    return {
      newsId: 0,
      projectId: 0,
      newsDetail: {
        title: '', // 标题
        cover: '', // 封面
        sketch: '', // 描述
        content: '', // 富文本
      },
      uploadUrl: '',
      headers: {},
      photoLoading: false,
      visible: false,
      wangEditorDisable: false,
    };
  },
  mounted() {
    this.uploadUrl = UPLOAD;
    this.headers['authorization'] = getCookie('Authorization');
    this.newsId = this.$route.params.id;
    if (this.newsId == 0) {
      return;
    }
    if (this.user.type === '2') {
      this.admin();
    } else {
      this.superAdmin();
      this.wangEditorDisable = true;
    }
  },
  computed: {
    ...mapGetters('account', ['user']),
  },
  methods: {
    back() {
      window.history.go(-1);
    },
    async superAdmin() {
      // this.newsId = this.$route.params.id;
      // let res = await getNewsByIdAdminApi({
      //   id: this.newsId,
      // });
      // this.newsDetail = res.data;
    },
    async admin() {
      let res = await getNewsByIdApi({
        id: this.newsId,
      });
      this.newsDetail = res.data;
    },
    showModal() {
      this.visible = true;
    },
    submit() {
      if (!this.newsDetail.cover) {
        this.$message.error('请选择封面');
        this.visible = false;
        return;
      }
      if (!this.newsDetail.title) {
        this.$message.error('标题不能为空');
        this.visible = false;
        return;
      }
      if (!this.newsDetail.sketch) {
        this.$message.error('描述不能为空');
        this.visible = false;
        return;
      }
      if (!this.newsDetail.content) {
        this.$message.error('内容不能为空');
        this.visible = false;
        return;
      }
      if (this.newsId != 0) {
        //编辑
        editNewsApi(this.newsDetail)
          .then((res) => {
            this.$message.success(res.msg);
            setTimeout(() => {
              window.history.go(-1);
            }, 500);
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      } else {
        //新增
        addNewsApi(this.newsDetail)
          .then((res) => {
            this.$message.success(res.msg);
            setTimeout(() => {
              window.history.go(-1);
            }, 500);
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      }
    },
    cancel() {
      this.visible = false;
    },
    // 图片上传
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.photoLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.newsDetail.cover = info.file.response.path;
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.img = imageUrl;
          this.photoLoading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp';
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.upload {
  width: 5rem;
  height: 5rem;
  border: solid;
}
img {
  width: 10rem;
  height: 10rem;
}
.actions {
  text-align: center;
  padding-right: 5rem;
  .ant-btn {
    margin-right: 10px;
  }
}
</style>
